<?php

namespace App\Model;

use EasySwoole\DDL\Enum\Character;
use EasySwoole\DDL\Enum\Engine;
use EasySwoole\ORM\AbstractModel;
use EasySwoole\ORM\Exception\Exception;
use EasySwoole\ORM\Utility\Schema\Table;
use Throwable;

class NewsCommentModel extends AbstractModel
{
    protected $tableName = 't_community_dynamic_comment';
    protected $autoTimeStamp = true; // 自动写入create_time和update_time 这两个字段是int

    /**
     * @throws Exception
     * @throws Throwable
     * @throws \EasySwoole\Mysqli\Exception\Exception
     */
    public function getDynamic($where)
    {
        $where['is_deleted'] = 0;
        return $this->order('id', 'desc')->get($where);
    }

    /**
     * @throws Throwable
     * @throws Exception
     */
    public function addDynamic($where)
    {
        try {
            $model = new NewsModel();
            $dynamic = $model->getNews(['id' => $where['gid']]);
            if (!$dynamic) {
                return false;
            }
            // 开启事务
            \EasySwoole\ORM\DbManager::getInstance()->startTransaction();

            $this->data($where, false);
            $res = $this->save();


            $upRes = $model->update(['comment' => ($dynamic->comment + 1)], ['id' => $where['gid']]);

            // 提交事务
            \EasySwoole\ORM\DbManager::getInstance()->commit();
            return $res;
        } catch (Throwable $e) {
            // 回滚事务
            \EasySwoole\ORM\DbManager::getInstance()->rollback();
            return false;
        }

    }

    public function schemaInfo(bool $isCache = true): Table
    {
        $table = new Table($this->tableName);

        $table->setIfNotExists();
        $table->setTableEngine(Engine::INNODB);
        $table->setTableCharset(Character::UTF8MB4_GENERAL_CI);
        $table->setTableComment('新闻评论表');

        $table->colInt('id')->setIsAutoIncrement()->setIsPrimaryKey(true)->setColumnComment("ID");
        $table->colInt('uid', 25)->setDefaultValue(0)->setIsNotNull()->setColumnComment('用户id');
        $table->colInt('gid', 25)->setDefaultValue(0)->setIsNotNull()->setColumnComment('动态id');
        $table->colInt('nid', 25)->setDefaultValue(0)->setIsNotNull()->setColumnComment('评论id');
        $table->colInt('likeNum', 25)->setDefaultValue(0)->setIsNotNull()->setColumnComment('点赞数量');
        $table->colVarChar("content", 255)->setDefaultValue("")->setColumnComment("评论内容");
        $table->colTinyInt('is_read', 1)->setDefaultValue(0)->setIsNotNull()->setColumnComment('是否已读：0.未读，1.已读');
        $table->colTinyInt('is_deleted', 1)->setDefaultValue(0)->setIsNotNull()->setColumnComment('是否删除：0.未删除，1.已删除');
        $table->colInt('create_time', 10)->setDefaultValue(0)->setIsNotNull()->setColumnComment('创建时间戳');
        $table->colInt('update_time', 10)->setDefaultValue(0)->setIsNotNull()->setColumnComment('更新时间戳');

        $table->indexNormal('cuid_index', 'uid');
        $table->indexNormal('gid_index', 'gid');

        return $table;
    }
}